import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:magma/heartbeat/helpers/magma_tap.dart';
import 'package:qlevar_router/qlevar_router.dart';
import 'package:stacked/stacked.dart';
import '../../heartbeat/helpers/magma_constant.dart';
import '../../heartbeat/helpers/magma_text_style.dart';
import '../../heartbeat/helpers/magma_color.dart';
import '../../heartbeat/helpers/magma_router.dart';
import '../../heartbeat/helpers/magma_toast.dart';
import '../../heartbeat/parts/magma_report_dialog.dart';
import '../../comms_link/app_state.dart';
import '../../heartbeat/blueprint/user_model.dart';
import '../../heartbeat/blueprint/club_model.dart';

/// 俱乐部群聊页面视图模型
class GroupChatNavigatorViewModel extends BaseViewModel {
  String _clubId = '';
  String get clubId => _clubId;

  final TextEditingController messageController = TextEditingController();

  /// 获取当前用户
  UserModel? get currentUser => appState.userStore.currentUser;

  /// 检查是否已登录
  bool get isLoggedIn => appState.userStore.isLoggedIn;

  /// 初始化数据
  void setupData(String clubId) {
    _clubId = clubId;
    notifyListeners();
  }

  /// 获取俱乐部信息
  ClubModel? get club {
    return appState.clubManager.locateClub(_clubId);
  }

  /// 获取俱乐部消息列表
  List<ClubMessageModel> get messages {
    return appState.clubManager.retrieveClubMessages(_clubId);
  }

  /// 根据用户ID获取用户
  UserModel? getUserById(String userId) {
    return appState.userStore.getUserById(userId);
  }

  /// 发送消息
  Future<bool> sendMessage() async {
    if (!isLoggedIn) return false;
    if (messageController.text.trim().isEmpty) return false;

    final result = await appState.clubManager.dispatchMessage(
      clubId: _clubId,
      userId: currentUser!.id,
      content: messageController.text.trim(),
    );

    if (result) {
      messageController.clear();
      notifyListeners();
    }

    return result;
  }

  /// 清空聊天记录
  Future<bool> clearMessages() async {
    final result = await appState.clubManager.clearClubMessages(_clubId);
    if (result) notifyListeners();
    return result;
  }

  @override
  void dispose() {
    messageController.dispose();
    super.dispose();
  }
}

/// 俱乐部群聊页面
class GroupChatStory extends StatefulWidget {
  final String clubId;

  const GroupChatStory({super.key, required this.clubId});

  @override
  State<GroupChatStory> createState() => _GroupChatStoryState();
}

class _GroupChatStoryState extends State<GroupChatStory> {
  final ScrollController _scrollController = ScrollController();

  @override
  void dispose() {
    _scrollController.dispose();
    super.dispose();
  }

  void _scrollToBottom() {
    if (_scrollController.hasClients) {
      Future.delayed(const Duration(milliseconds: 100), () {
        _scrollController.animateTo(
          _scrollController.position.maxScrollExtent,
          duration: const Duration(milliseconds: 300),
          curve: Curves.easeOut,
        );
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return ViewModelBuilder<GroupChatNavigatorViewModel>.reactive(
      viewModelBuilder: () => GroupChatNavigatorViewModel(),
      onViewModelReady: (viewModel) {
        viewModel.setupData(widget.clubId);
        WidgetsBinding.instance.addPostFrameCallback((_) => _scrollToBottom());
      },
      builder: (context, viewModel, child) {
        final club = viewModel.club;

        if (club == null) {
          return Scaffold(
            backgroundColor: MagmaColor.black,
            body: Center(
              child: Text(
                'Club not found',
              ).inter(fontSize: 16.sp, color: MagmaColor.white),
            ),
          );
        }

        WidgetsBinding.instance.addPostFrameCallback((_) => _scrollToBottom());

        return Scaffold(
          backgroundColor: MagmaColor.black,
          appBar: AppBar(
            backgroundColor: MagmaColor.black,
            leading: MagmaTap(
              onTap: () => QR.back(),
              child: Container(
                padding: EdgeInsets.all(14.w),
                child: Image.asset(
                  MagmaConstant.back,
                  width: 16.w,
                  height: 16.w,
                  color: MagmaColor.white,
                ),
              ),
            ),
            title: Text('Club Group Chat').blackHanSans(
              fontSize: 24.sp,
              color: MagmaColor.white,
              fontWeight: FontWeight.w700,
            ),
            centerTitle: true,
            actions: [
              MagmaTap(
                onTap: () => _showReportDialog(context, viewModel),
                child: Padding(
                  padding: EdgeInsets.only(right: 20.w),
                  child: Image.asset(
                    MagmaConstant.report,
                    width: 26.w,
                    height: 26.w,
                    color: MagmaColor.white,
                  ),
                ),
              ),
            ],
          ),
          body: Column(
            children: [
              // 成员数量提示
              _buildMemberCountHeader(club, viewModel),

              // 消息列表
              Expanded(
                child:
                    viewModel.messages.isEmpty
                        ? Center(
                          child: Text('No messages yet').inter(
                            fontSize: 14.sp,
                            color: MagmaColor.white.withOpacity(0.5),
                          ),
                        )
                        : ListView.builder(
                          controller: _scrollController,
                          padding: EdgeInsets.symmetric(
                            horizontal: 16.w,
                            vertical: 12.h,
                          ),
                          itemCount: viewModel.messages.length,
                          itemBuilder: (context, index) {
                            final message = viewModel.messages[index];
                            final user = viewModel.getUserById(message.userId);
                            final isCurrentUser =
                                viewModel.isLoggedIn &&
                                message.userId == viewModel.currentUser?.id;

                            return _buildMessageItem(
                              message,
                              user,
                              isCurrentUser,
                            );
                          },
                        ),
              ),

              // 输入框
              _buildMessageInput(viewModel),
            ],
          ),
        );
      },
    );
  }

  /// 构建成员数量头部
  Widget _buildMemberCountHeader(
    ClubModel club,
    GroupChatNavigatorViewModel viewModel,
  ) {
    return Container(
      padding: EdgeInsets.symmetric(vertical: 12.h),
      decoration: BoxDecoration(
        border: Border(
          bottom: BorderSide(
            color: MagmaColor.white.withOpacity(0.1),
            width: 1.w,
          ),
        ),
      ),
      child: MagmaTap(
        onTap: () {
          QR.to(MagmaRouter.memberListPath.replaceAll(':clubId', club.id));
        },
        child: RichText(
          textAlign: TextAlign.center,
          text: TextSpan(
            text: 'The club has a total of ',
            style: TextStyle(
              fontFamily: 'BlackHanSans',
              fontSize: 14.sp,
              color: MagmaColor.white,
              fontWeight: FontWeight.w400,
            ),
            children: [
              TextSpan(
                text: '${club.memberIds.length} members',
                style: TextStyle(
                  fontFamily: 'BlackHanSans',
                  fontSize: 14.sp,
                  color: MagmaColor.white,
                  fontWeight: FontWeight.w700,
                ),
              ),
              TextSpan(
                text: '…',
                style: TextStyle(
                  fontFamily: 'BlackHanSans',
                  fontSize: 14.sp,
                  color: MagmaColor.green,
                  fontWeight: FontWeight.w700,
                ),
              ),
              TextSpan(
                text: 'all',
                style: TextStyle(
                  fontFamily: 'BlackHanSans',
                  fontSize: 14.sp,
                  color: MagmaColor.green,
                  fontWeight: FontWeight.w700,
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  /// 构建消息项
  Widget _buildMessageItem(
    ClubMessageModel message,
    UserModel? user,
    bool isCurrentUser,
  ) {
    return Padding(
      padding: EdgeInsets.only(bottom: 16.h),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        mainAxisAlignment:
            isCurrentUser ? MainAxisAlignment.end : MainAxisAlignment.start,
        children: [
          if (!isCurrentUser) ...[
            // 他人消息：左侧头像
            CircleAvatar(
              radius: 20.r,
              backgroundImage: AssetImage(
                user?.avatar ?? MagmaConstant.avatar1,
              ),
            ),
            SizedBox(width: 8.w),
          ],

          // 消息气泡
          Flexible(
            child: Container(
              padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 12.h),
              decoration: BoxDecoration(
                color:
                    isCurrentUser
                        ? MagmaColor.green
                        : MagmaColor.white.withOpacity(0.15),
                borderRadius:
                    isCurrentUser
                        ? BorderRadius.only(
                          topLeft: Radius.circular(16.r),
                          topRight: Radius.circular(2.r),
                          bottomLeft: Radius.circular(16.r),
                          bottomRight: Radius.circular(16.r),
                        )
                        : BorderRadius.only(
                          topLeft: Radius.circular(2.r),
                          topRight: Radius.circular(16.r),
                          bottomLeft: Radius.circular(16.r),
                          bottomRight: Radius.circular(16.r),
                        ),
              ),
              child: Text(message.content).inter(
                fontSize: 14.sp,
                color: isCurrentUser ? MagmaColor.black : MagmaColor.white,
                fontWeight: FontWeight.w400,
              ),
            ),
          ),

          if (isCurrentUser) ...[
            // 当前用户消息：右侧头像
            SizedBox(width: 8.w),
            CircleAvatar(
              radius: 20.r,
              backgroundImage: AssetImage(
                user?.avatar ?? MagmaConstant.avatar1,
              ),
            ),
          ],
        ],
      ),
    );
  }

  /// 构建消息输入框
  Widget _buildMessageInput(GroupChatNavigatorViewModel viewModel) {
    return Column(
      mainAxisSize: MainAxisSize.min,
      children: [
        // 装饰图片
        Image.asset(
          MagmaConstant.decoration,
          width: double.infinity,
          fit: BoxFit.fitWidth,
        ),

        // 输入框区域
        Container(
          padding: EdgeInsets.fromLTRB(
            16.w,
            12.h,
            16.w,
            MediaQuery.of(context).padding.bottom + 12.h,
          ),
          color: MagmaColor.black,
          child: SizedBox(
            height: 56.h,
            child: Container(
              decoration: BoxDecoration(
                color: MagmaColor.white,
                borderRadius: BorderRadius.circular(12.r),
              ),
              child: Row(
                children: [
                  // 输入框
                  Expanded(
                    child: TextField(
                      controller: viewModel.messageController,
                      style: TextStyle(
                        color: MagmaColor.black,
                        fontSize: 14.sp,
                      ),
                      decoration: InputDecoration(
                        hintText: 'Say Something...',
                        hintStyle: TextStyle(
                          color: MagmaColor.black.withOpacity(0.6),
                          fontSize: 14.sp,
                        ),
                        border: InputBorder.none,
                        contentPadding: EdgeInsets.symmetric(
                          horizontal: 20.w,
                          vertical: 16.h,
                        ),
                      ),
                      onSubmitted: (_) => viewModel.sendMessage(),
                    ),
                  ),

                  // Send 按钮（在输入框内）
                  Padding(
                    padding: EdgeInsets.only(right: 8.w),
                    child: MagmaTap(
                      onTap: viewModel.sendMessage,
                      child: Container(
                        padding: EdgeInsets.symmetric(
                          horizontal: 20.w,
                          vertical: 10.h,
                        ),
                        decoration: BoxDecoration(
                          color: MagmaColor.purple,
                          borderRadius: BorderRadius.circular(12.r),
                        ),
                        child: Text('Send').blackHanSans(
                          fontSize: 18.sp,
                          color: MagmaColor.black,
                          fontWeight: FontWeight.w400,
                        ),
                      ),
                    ),
                  ),
                ],
              ),
            ),
          ),
        ),
      ],
    );
  }

  /// 显示举报对话框
  void _showReportDialog(
    BuildContext context,
    GroupChatNavigatorViewModel viewModel,
  ) {
    MagmaReportDialog.showReportDialog(
      context,
      title: 'Report Club',
      subtitle: 'Please select a reason for reporting this club',
      onReportSubmitted: (option) async {
        // 清空聊天记录
        await viewModel.clearMessages();
        if (!mounted) return;
        // 返回上一页
        QR.back();
        MagmaToast.success(context, title: 'Report submitted successfully');
      },
    );
  }
}
